Page({
  data: {
    // 弹窗确认
    show: true,
    //
    show1: false,
  },

  getUserInfo({ detail: { iv, encryptedData } }) {
    const _this = this
    let code = wx.getStorageSync('code')
    if (code) {
      _this._login({ code, iv, encryptedData })
    } else {
      wx.login({
        success: (res) => {
          if (res.code) {
            _this._login({ code: res.code, iv, encryptedData })
          } else {
            console.log('获取用户登录态失败：' + res.errMsg)
          }
        },
      })
    }
  },
  async _login({ code, encryptedData, iv }) {
    let { data } = await wx.requestAsync({
      url: '/login',
      data: {
        code,
        encryptedData,
        iv,
      },
    })
    wx.setStorage({
      key: 'token',
      data: data.token,
    })

    this._getUser()
    this.setData({
      show: false,
    })
  },
  onClose() {
    this.setData({ close: false })
  },

  ////////绑定手机号
  _getPhone({ detail: { errMsg, iv, encryptedData } }) {
    const _this = this
    wx.login({
      success: ({ code }) => {
        if (code) {
          wx.checkSession({
            success(res) {
              console.log(res)
              if (errMsg == 'getPhoneNumber:fail user deny') {
                //拒绝授权
              } else {
                //同意授权
                _this._bindPhone({ code, encryptedData, iv, errMsg }) // 调取后台接口绑定手机号
              }
            },
            fail() {},
          })
        } else {
          console.log('登录失败！' + errMsg)
        }
      },
    })
  },
  // 绑定手机号
  async _bindPhone({ code, encryptedData, iv }) {
    let res = await wx.requestAsync({
      url: '/bind/phone',
      data: { code, encryptedData, iv },
    })
    if (res.code == 0) {
      this.setData({
        show1: false,
      })
      wx.navigateBack({
        delta: 1,
      })
      // wx.switchTab({
      //   url: '/pages/home/home',
      // })
    }
  },
  // 获取用户信息
  async _getUser() {
    let {
      code,
      data: { phone },
    } = await wx.requestAsync({
      url: '/user/info',
    })
    if (code == 0) {
      if (phone) {
        wx.navigateBack({
          delta: 1,
        })

        // wx.switchTab({
        //   url: '/pages/home/home',
        // })
      } else {
        this.setData({
          show1: true,
        })
      }
    }
  },
})
